import {
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProForm,
  ProFormList,
  ProFormDigit,
  ProFormInstance,
} from '@ant-design/pro-components';
import { Button, FormListOperation, Modal } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import { message, Upload, Divider } from 'antd';
import { goodsStateOptions, saleTypeOptions } from '@/const';
import { addGoods, getCategoryList, updateGoods } from '@/services/goods';
import { RcFile, UploadChangeParam, UploadFile } from 'antd/es/upload';
import { PlusOutlined } from '@ant-design/icons';
import { UpdateFormProps, GoodsSkuType, GoodsPicType, GoodsItemType, CategoryType } from '../type'

const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

const defaultSkuItem = {
  inch: '10+6',
  edible: '8-10',
  "specs": "3磅", // 规格
  "stock": 100,// 库存
  "price": 22900, // 价格
  "linePrice": 39400, // 划线价格
  "goodsState": 1,//  商品状态 1:可售 2:不可售 3:部分可售
}

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: GoodsItemType) => {
  const hide = message.loading('正在添加');
  try {
    await addGoods({ ...fields });
    hide();
    message.success('添加成功！');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败！');
    return false;
  }
};

/**
 * @param fields
 */
const handleUpdate = async (fields: GoodsItemType) => {
  const hide = message.loading('正在编辑');
  try {
    await updateGoods({ ...fields });
    hide();
    message.success('编辑成功！');
    return true;
  } catch (error) {
    hide();
    message.error('编辑失败！');
    return false;
  }
};

const UpdateForm: React.FC<UpdateFormProps> = (props) => {
  const formRef = useRef<ProFormInstance>();
  const [mainPic, setMainPic] = useState<string>('');
  const [detailPicList, setDetailPicList] = useState<Array<GoodsPicType>>([]);
  const [bannerPicList, setBannerPicList] = useState<Array<GoodsPicType>>([]);
  const [homePicList, setHomePicList] = useState<Array<GoodsPicType>>([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const { mode, values } = props;

  const [categoryList, setCategoryList] = useState<Array<CategoryType>>([]);

  const handleMainPicChange = (info: UploadChangeParam<UploadFile>) => {
    console.log(formRef.current)
    if (info.file.status === 'done') {
      setMainPic(info.file.response.data.fullUrl);
    }
    if (info.file.status === 'error' || info.file.status === 'removed') {
      setMainPic('');
    }
  }

  const handleDetailPicChange = (info: UploadChangeParam<UploadFile>,) => {
    if (info.file.status === 'done') {
      info.file.url = info.file.response.data.fullUrl
    }
    if (info.file.status === 'error' || info.file.status === 'removed' || info.file.status === 'done') {
      const list = info.fileList.map((item, index): GoodsPicType => {
        return {
          "type": 1,
          "url": item.url, 
          "pic": item.url,// url
          "sort": index,
        }
      })
      setDetailPicList(list)
    }
  }

  const handleBannerPicChange = (info: UploadChangeParam<UploadFile>,) => {
    if (info.file.status === 'done') {
      info.file.url = info.file.response.data.fullUrl
    }
    if (info.file.status === 'error' || info.file.status === 'removed' || info.file.status === 'done') {
      const list = info.fileList.map((item, index): GoodsPicType => {
        return {
          "type": 0,
          "url": item.url, 
          "pic": item.url,// url
          "sort": index,
        }
      })
      setBannerPicList(list)
    }
  }

  const handleHomePicChange = (info: UploadChangeParam<UploadFile>,) => {
    if (info.file.status === 'done') {
      info.file.url = info.file.response.data.fullUrl
    }
    if (info.file.status === 'error' || info.file.status === 'removed' || info.file.status === 'done') {
      const list = info.fileList.map((item: {[key: string]: any}, index): GoodsPicType => {
        return {
          id: item.id || '',
          "type": 2,
          "url": item.url, 
          "pic": item.url,// url
          "sort": index,
        }
      })
      setHomePicList(list)
    }
  }

  const handleSpecPicChange = (info: UploadChangeParam<UploadFile>, action: FormListOperation & {
      getCurrentRowData: () => any;
      setCurrentRowData: (data: any) => void;
  }) => {
    const picItem = action.getCurrentRowData()
    if (info.file.status === 'done') {
      action.setCurrentRowData({
        ...picItem,
        pic: info.file.response.data.fullUrl
      })
    }
  };

  const handleCancel = () => setPreviewOpen(false);

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
    }

    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };


  const getOtherPic = () => {
    let result: any[] = []
    if (detailPicList && detailPicList.length) {
      result = result.concat(detailPicList)
    }
    if (bannerPicList && bannerPicList.length) {
      result = result.concat(bannerPicList)
    }
    if (homePicList && homePicList.length) {
      result = result.concat(homePicList)
    }
    return result
  }

  const getFormParams = (form: GoodsItemType, originForm: Partial<GoodsItemType>) => {
    const categoryItem = categoryList.find(item => item.id === form.categoryId)
    return {
      id: originForm && originForm.id,
      name: form.name,
      categoryId: form.categoryId,
      categoryName: categoryItem?.categoryName,
      description: form.description,
      mainPic: mainPic,
      isOnSale: form.isOnSale,
      goodsState: form.goodsState,
      alias: form.alias,
      mallGoodsSkus: form.mallGoodsSkus.map((item: GoodsSkuType) => {
        return {
          ...item,
          pic: item.pic
        }
      }),
      mallGoodsPics: getOtherPic(),
      channel: originForm.channel || 0,
      materielState: originForm.materielState || 2,
    }
  }

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  useEffect(() => {
    getCategoryList().then(res => {
      setCategoryList(res.data || []);
    })
  }, [])

  useEffect(() => {
    if (values && values.id) {
      setMainPic(values.mainPic || '');
      if (values.mallGoodsPics) {
        setHomePicList(values.mallGoodsPics.filter(item => item.type === 2));
        setDetailPicList(values.mallGoodsPics.filter(item => item.type === 1));
        setBannerPicList(values.mallGoodsPics.filter(item => item.type === 0));
      }
    } else {
      setMainPic('');
      setHomePicList([]);
      setDetailPicList([]);
      setBannerPicList([]);
    }
  }, [values])

  return (
    <>
    <Modal
      width={1000}
      bodyStyle={{ padding: '32px 40px 48px' }}
      destroyOnClose
      title={mode === 'add' ? '新增商品' : '编辑商品'}
      open={props.updateModalOpen}
      onCancel={() => {
        props.onCancel();
      }}
      maskClosable={false}
      footer={false}
    >
      <ProForm
        onFinish={async (form) => {
          console.log(values);
          const val1 = await formRef.current?.validateFields();
          console.log('validateFields:', val1);
          const val2 = await formRef.current?.validateFieldsReturnFormatValue?.();
          console.log('validateFieldsReturnFormatValue:', val2);
          const params = getFormParams(form, values);
          if (mode === 'add') {
            handleAdd(params).then(res => {
              res && props.onSubmit()
            })
          } else if (mode === 'edit') {
            handleUpdate(params).then(res => {
              res && props.onSubmit()
            })
          }
        }}
        onFinishFailed={(errorInfo) => {
          const { errorFields } = errorInfo;
          let errMsg = '请先完善表单信息！'
          if (errorFields && errorFields.length) {
            errMsg = errMsg + errorFields[0].errors[0]
          }
          message.error(errMsg);
        }}
        formRef={formRef}
        initialValues={{
          categoryId: categoryList && categoryList[0] && categoryList[0].id,
          isOnSale: 1,
          goodsState: 1,
          ...values
        }}
        submitter={{
          render: function(childProps, dom) {
            return (<div style={{textAlign: 'right'}}>
              <Button onClick={() => props.onCancel()} style={{marginRight: 10}}>取消</Button>
              {dom[1]}
            </div>)
          }
        }}
      >
        <ProForm.Group>
          <ProFormText
            name="name"
            required
            label="商品名称"
            placeholder="请输入商品名称"
            rules={[{ required: true, message: '请输入商品名称' }]}
          />
          <ProFormText
            name="alias"
            label="别名"
            placeholder="请输入别名"
          />
          <ProFormTextArea
            width="xl"
            name="description"
            label="描述"
            placeholder="请输入描述"
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormSelect
            options={
              categoryList.map((item) => {
                return {
                  label: item.categoryName,
                  value: item.id,
                }
              })
            }
            name="categoryId"
            label="商品类别"
            rules={[{ required: true, message: '请选择商品类别' }]}
          />
          <ProFormSelect
            options={saleTypeOptions}
            name="isOnSale"
            label="商品上架状态"
          />
          <ProFormSelect
            options={goodsStateOptions}
            name="goodsState"
            label="商品可售状态"
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProForm.Item label="商品主图"
            name="mainPic"
            rules={[{ required: true, message: '请上传商品主图' }]}>
            <Upload
              name="file"
              listType="picture-card"
              showUploadList={false}
              action="/api/xmbz-distribution/mallGoods/fileoss"
              data={{type: '1'}}
              beforeUpload={beforeUpload}
              onChange={handleMainPicChange}
            >
              {mainPic ? <img src={mainPic} alt="avatar" style={{ width: '100%',height: '100%' }} /> : uploadButton}
            </Upload>
          </ProForm.Item>
        </ProForm.Group>
        <ProForm.Group>
          <ProFormList
            initialValue={[defaultSkuItem]}
            creatorRecord={defaultSkuItem}
            min={1}
            alwaysShowItemLabel
            label="商品规格" name="mallGoodsSkus"
            creatorButtonProps={{
              creatorButtonText: '添加规格项',
            }}
            onAfterAdd={(...data) => {
              console.log(data)
            }}>
            {(f, index, action) => {
              const item = action.getCurrentRowData()
              return (
                <>
                  <Divider></Divider>
                  <ProForm.Group title={`规格 ${index + 1}`}>
                    <ProFormText
                      name="skuCode"
                      placeholder="sku码：4.001.0366"
                      label="sku码"
                      rules={[{ required: true, message: '请输入sku码' }]}
                    />
                    <ProFormText
                      name="inch"
                      placeholder="英寸：10+6"
                      label="英寸"
                    />
                    <ProFormText
                      name="edible"
                      placeholder="食用人数：8-10"
                      label="食用人数"
                    />
                    <ProFormText
                      name="specs"
                      placeholder="规格：3磅"
                      label="规格"
                    />
                    <ProFormDigit
                      name="stock"
                      placeholder="库存：100"
                      label="库存"
                    />
                    <ProFormDigit
                      name="price"
                      placeholder="价格：22900（分）"
                      label="价格（分）"
                    />
                    <ProFormDigit
                      name="linePrice"
                      placeholder="划线价格：39400（分）"
                      label="划线价格（分）"
                    />
                    <ProFormSelect
                      options={goodsStateOptions}
                      name="goodsState"
                      placeholder="商品可售状态"
                      label="商品可售状态"
                    />
                    <ProForm.Item label="规格图" name="pics">
                      <Upload
                        name="file"
                        data={{type: '1'}}
                        listType="picture-card"
                        action="/api/xmbz-distribution/mallGoods/fileoss"
                        showUploadList={false}
                        beforeUpload={beforeUpload}
                        onChange={(info) => handleSpecPicChange(info, action)}
                      >
                        {item.pic ? <img src={item.pic} alt="avatar" style={{ width: '100%', height: '100%' }} /> : uploadButton}
                      </Upload>
                    </ProForm.Item>
                  </ProForm.Group>
                </>
              )
            }}
          </ProFormList>
        </ProForm.Group>
        <ProForm.Group>
          <ProForm.Item label="商品首页图" name="homePicFileList">
            <Upload
              name="file"
              data={{type: '1'}}
              listType="picture-card"
              action="/api/xmbz-distribution/mallGoods/fileoss"
              defaultFileList={(homePicList || []).filter(item => item.type === 2).map(item => {
                return {
                  uid: item.id,
                  name: '',
                  url: item.pic || item.url || ''
                }
              }) as UploadFile[]}
              beforeUpload={beforeUpload}
              onChange={handleHomePicChange}
              onPreview={handlePreview}
            >
              {uploadButton}
            </Upload>
          </ProForm.Item>
        </ProForm.Group>
        <ProForm.Group>
          <ProForm.Item label="商品详情图" name="detailPicFileList">
            <Upload
              name="file"
              data={{type: '1'}}
              listType="picture-card"
              action="/api/xmbz-distribution/mallGoods/fileoss"
              defaultFileList={(detailPicList || []).filter(item => item.type === 1).map(item => {
                return {
                  uid: item.id,
                  name: '',
                  url: item.pic || item.url || ''
                }
              }) as UploadFile[]}
              beforeUpload={beforeUpload}
              onChange={handleDetailPicChange}
              onPreview={handlePreview}
            >
              {uploadButton}
            </Upload>
          </ProForm.Item>
        </ProForm.Group>
        <ProForm.Group>
          <ProForm.Item label="商品banner图" name="bannerPicFileList">
            <Upload
              name="file"
              data={{type: '1'}}
              listType="picture-card"
              action="/api/xmbz-distribution/mallGoods/fileoss"
              defaultFileList={(bannerPicList || []).filter(item => item.type === 0).map(item => {
                return {
                  uid: item.id,
                  name: '',
                  url: item.pic || item.url || ''
                }
              }) as UploadFile[]}
              beforeUpload={beforeUpload}
              onChange={handleBannerPicChange}
              onPreview={handlePreview}
            >
              {uploadButton}
            </Upload>
          </ProForm.Item>
        </ProForm.Group>
      </ProForm>
    </Modal>
    <Modal open={previewOpen} title='' footer={null} onCancel={handleCancel}>
      <img alt="example" style={{ width: '100%' }} src={previewImage} />
    </Modal>
    </>
  );
};

export default UpdateForm;
